<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class BaseController extends Controller
{
    /**
     * 成功响应
     */
    protected function success($data = null, string $message = '操作成功', int $code = 200): JsonResponse
    {
        return response()->json([
            'success' => true,
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'timestamp' => now()->toISOString(),
            'request_id' => uniqid()
        ], $code);
    }

    /**
     * 错误响应
     */
    protected function error(string $message = '操作失败', int $code = 400, $errors = null): JsonResponse
    {
        $response = [
            'success' => false,
            'code' => $code,
            'message' => $message,
            'timestamp' => now()->toISOString(),
            'request_id' => uniqid()
        ];

        if ($errors) {
            $response['errors'] = $errors;
        }

        return response()->json($response, $code);
    }

    /**
     * 分页响应
     */
    protected function paginate($data, string $message = '获取成功'): JsonResponse
    {
        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $data->items(),
            'pagination' => [
                'total' => $data->total(),
                'per_page' => $data->perPage(),
                'current_page' => $data->currentPage(),
                'last_page' => $data->lastPage(),
                'from' => $data->firstItem(),
                'to' => $data->lastItem(),
            ],
            'timestamp' => now()->toISOString(),
            'request_id' => uniqid()
        ]);
    }

    /**
     * 验证请求数据
     */
    protected function validateRequest($request, array $rules, array $messages = []): array
    {
        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            throw ValidationException::withMessages($validator->errors()->toArray());
        }

        return $validator->validated();
    }

    /**
     * 获取当前用户信息
     */
    protected function getCurrentUser()
    {
        return auth()->user();
    }

    /**
     * 检查权限
     */
    protected function checkPermission(string $permission): bool
    {
        $user = $this->getCurrentUser();
        return $user && $user->hasPermission($permission);
    }

    /**
     * 检查角色
     */
    protected function checkRole(string $role): bool
    {
        $user = $this->getCurrentUser();
        return $user && $user->hasRole($role);
    }

    /**
     * 记录操作日志
     */
    protected function logOperation(string $action, string $module, array $data = []): void
    {
        // 这里可以实现操作日志记录逻辑
        // 例如：记录到数据库或发送到日志服务
    }
}
